package cn.iocoder.yudao.module.member.fans.service;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.dao.query.CoreLambdaQueryWrapper;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.api.member.user.MemberUserApi;
import cn.iocoder.yudao.module.member.fans.dal.dataobject.MemberFansDO;
import cn.iocoder.yudao.module.member.fans.dal.mysql.MemberFansMapper;
import cn.iocoder.yudao.module.member.fans.vo.MemberFansPageReqVO;
import cn.iocoder.yudao.module.member.fans.vo.MemberFansRespVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.api.member.ErrorCodeConstants.FANS_FOLLOW_DUPLICATE;
import static cn.iocoder.yudao.module.api.member.ErrorCodeConstants.FANS_FOLLOW_SELF_FORBIDDEN;

/**
 * 视频粉丝 Service 实现类
 *
 * @author 山野羡民
 */
@Service
@Validated
public class MemberFansServiceImpl implements MemberFansService {

    @Resource
    private MemberFansMapper memberFansMapper;
    @Resource
    private MemberUserApi memberUserApi;

    @Override
    public boolean isFollow(Long myUserId, Long targetUserId) {
        return queryRelationship(targetUserId, myUserId) != null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void doFollow(Long myUserId, Long targetUserId) {
        // 自己不能关注自己
        if (Objects.equals(myUserId, targetUserId)) {
            throw exception(FANS_FOLLOW_SELF_FORBIDDEN);
        }
        if (queryRelationship(targetUserId, myUserId) != null) {
            throw exception(FANS_FOLLOW_DUPLICATE);
        }
        // 确保两个用户存在
        memberUserApi.validateUser(myUserId);
        memberUserApi.validateUser(targetUserId);
        MemberFansDO fansDO = new MemberFansDO();
        fansDO.setUserId(targetUserId);
        fansDO.setFansUserId(myUserId);
        // 我关注对方时，判断对方是否关注我，如果关注我，那么双方都要互为朋友关系
        MemberFansDO relationship = queryRelationship(myUserId, targetUserId);
        if (relationship != null) {
            fansDO.setFriend(true);
            relationship.setFriend(true);
            memberFansMapper.updateById(relationship);
        } else {
            fansDO.setFriend(false);
        }
        memberFansMapper.insert(fansDO);
        // 目标用户的粉丝+1，我的关注+1
        // TODO 发送系统消息：某某关注了我、某某和我成为了朋友
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancelFollow(Long myUserId, Long targetUserId) {
        // 我取关对方时，判断双方是否朋友关系，如果是，则需要取消双方的朋友关系
        MemberFansDO relationship = queryRelationship(targetUserId, myUserId);
        if (relationship != null && relationship.getFriend()) {
            // 抹除双方的朋友关系，第一步是更新自己的粉丝关联表记录，然后删除对方的粉丝关联表记录
            MemberFansDO pendingFans = queryRelationship(myUserId, targetUserId);
            if (pendingFans != null) {
                pendingFans.setFriend(false);
                memberFansMapper.updateById(pendingFans);
            }
        }
        // 删除自己的关注关联表记录，也即删除对方的粉丝关联表记录
        if (relationship != null) {
            memberFansMapper.deleteById(relationship);
        }
        // 目标用户的粉丝-1，我的关注-1
        // TODO 发送系统消息：某某取关了我
    }

    private MemberFansDO queryRelationship(Long vlogUserId, Long fansUserId) {
        List<MemberFansDO> list = memberFansMapper.selectList(new CoreLambdaQueryWrapper<MemberFansDO>()
                .eq(MemberFansDO::getUserId, vlogUserId)
                .eq(MemberFansDO::getFansUserId, fansUserId)
                .orderByDesc(MemberFansDO::getId));
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public PageResult<MemberFansRespVO> getMyFansPage(Long myUserId, PageParam reqVO) {
        PageResult<MemberFansDO> result = memberFansMapper.selectFansPage(reqVO, myUserId);
        return toRespVO(result);
    }

    @Override
    public PageResult<MemberFansRespVO> getMyFollowPage(Long myUserId, PageParam reqVO) {
        PageResult<MemberFansDO> result = memberFansMapper.selectFollowPage(reqVO, myUserId);
        return toRespVO(result);
    }

    @Override
    public PageResult<MemberFansRespVO> getMyFriendPage(Long myUserId, PageParam reqVO) {
        PageResult<MemberFansDO> result = memberFansMapper.selectFriendPage(reqVO, myUserId);
        return toRespVO(result);
    }

    @Override
    public PageResult<MemberFansRespVO> getFansPage(MemberFansPageReqVO reqVO) {
        PageResult<MemberFansDO> result = memberFansMapper.selectFansPage(reqVO);
        return toRespVO(result);
    }

    private PageResult<MemberFansRespVO> toRespVO(PageResult<MemberFansDO> result) {
        return BeanUtils.toBean(result, MemberFansRespVO.class);
    }

}
